<template>
  <!-- GF平台首页 -->
  <view class="page">
    <!-- 首页顶部导航 -->
    <toptab-bar class="toptab-bar"></toptab-bar>
    <!-- 内容 -->
    <view class="content">
      <swiper class="video-swiper"
              vertical="true"
              :current="activeVideoIndex"
              @change="onSwiperChange"
              v-if="isReceive"
      >
        <!-- 只让第一个视频能自动播放 -->

        <!-- <scroll-view scroll-y @scrolltolower="testReachBottom" class="page-scroll"> -->
        <!-- 				<swiper-item  class="video-swiper-item" >
                  <video src="http://vjs.zencdn.net/v/oceans.mp4"></video>
                </swiper-item>

                <swiper-item  class="video-swiper-item" >
                  <video src="https://record.gfinter.net/Live/video/0/4bfac3be884ae354d3d2c245332faf49/output_1980/2025-01-14-12:47:46-2025-01-14-14:36:44/index.m3u8"></video>
                </swiper-item> -->

        <swiper-item  class="video-swiper-item" v-for="(item,index) in displayItems" :key="index">
          <video-player
              v-if="displayIndexArr.includes(index)"
              :currentIndex="index"
              :activeIndex="activeVideoIndex"
              :autoplay="index===0"
              :data= "item"
              :video-option="videoOption"
              @video-error="onVideoError"
          ></video-player>
        </swiper-item>
        <!-- </scroll-view> -->
      </swiper>
    </view>
  </view>
</template>

<script setup>
import toptabBar from '@/pages/index/toptabbar/tabbar.vue';
import videoPlayer from '@/components/videoPlayer/videoPlayer.vue';
import {computed, onBeforeMount, onMounted, ref, watch} from 'vue';
import {onReachBottom} from '@dcloudio/uni-app';

import decLiveApi from '/api/dec/decIndex/decLiveApi.js'; //{ Get_live_list_API, Live_detail_API }
import decLatestApi from '/api/dec/decIndex/decLatestApi.js' //{ GF_latest_data_API }

// 正在播放的视频
const activeVideoIndex = ref(0);
// 分页逻辑
// 不传last id,pre id返回最新10，下拉更多时传入pre id返回id<pre id的10条

let PRE_ID = ref('');
let currentPage = ref(0);      // 第几页

// 所有播放资源
const displayItems = ref([]);

// 要播放的
const displayIndexArr = ref([0,1,2])

// 看过的视频 默认添加前3个
const indexItems = ref([0]);

// // 点击下一个视频
// const clickNext = ()=>{
// 	activeVideoIndex.value = activeVideoIndex.value+1;
// 	console.log('点击下一个')
// }

const videoOption = ref({});
// #ifdef MP-WEIXIN
videoOption.value.videoSize = 'contain';
videoOption.value.videoSize = 'fillCrop';
// #endif

// #ifndef MP-WEIXIN
videoOption.value.videoSize = 'cover';
// #endif

function onSwiperChange(event) {
  activeVideoIndex.value = event.detail.current;
  // console.log('activeIndex: ',activeVideoIndex.value);
  if(!indexItems.value.includes(activeVideoIndex.value)){
    indexItems.value.push(activeVideoIndex.value);
  }

  displayIndexArr.value.push(displayIndexArr.value.length);
}



// 当接收到子组件的视频出错事件时
const onVideoError = (index) => {
  console.log(`第 ${index} 个视频播放失败，尝试播放下一个视频`)
  // 切换到下一个视频
  // 确保下一个视频存在
  const nextIndex = index + 1
  if (nextIndex < displayItems.value.length) {
    activeVideoIndex.value = nextIndex
  }
  else {
    console.log('没有更多视频可播放了')
  }
}

// 数据是否接收到
const isReceive = ref(false);

async function init(){
  await GF_latest_data('', '', '', '5');
}


// visit_gfid='',last_id='',pre_id='',data_type_id='6'
// 刷最新列表
async function GF_latest_data(visit_gfid='',last_id='',pre_id='',data_type_id='5') {
  let params = {
    visit_gfid: visit_gfid,
    last_id : last_id,
    pre_id : pre_id,
    data_type_id : data_type_id,
  };
  try{
    let res = await decLatestApi.GF_latest_data_API(params);
    let lastDataItems = res.datas;
    // 翻页
    currentPage.value ++;
    // 不传last id,pre id返回最新10，下拉更多时传入pre id返回id<pre id的10条
    let minData_id = '9007199254740991';
    if(pre_id !== ''){
      minData_id = pre_id;
    }
    // 拿其中最早/旧的一条数据的data_id当成pre_id，作为下一次拉取数据的最新id
    for(let item of lastDataItems) {
      let thisData_id = item.id;
      minData_id = (minData_id > thisData_id) ? thisData_id : minData_id;
    }
    // console.log("minData_id:", minData_id);
    PRE_ID.value = minData_id
    const updatedItems = await Promise.all(
        lastDataItems.map(async item => {
              try{
                const detail = await Get_Live_detail_API(item.data_id); // 详情
                const url = detail.datas.live_source_rtmp_h;
                const data_type = item.data_type;
                const title = detail.datas.title;
                const live_type_name = detail.datas.live_type_name;
                const club_logo = detail.datas.club_logo;
                const club_name = detail.datas.club_name;
                const program = detail.program[0];
                return {
                  ...item,
                  detail,
                  url,
                  data_type,
                  title,
                  live_type_name,
                  club_logo,
                  club_name,
                  program
                };
              }catch(err){
                console.error(`Get_Live_detail_API获取数据项 ${item.data_id} 的详情信息失败`, err);
                return {
                  ...item,
                  error: true
                };
              }

            }
        ));
    // push回displayItems中
    updatedItems.forEach(item => displayItems.value.push(item));
    console.log("刷最新页面每个视频获得detail后的displayItems",displayItems.value);

    isReceive.value = true;
    // console.log("获得detail后的isReceive",isReceive.value);
  }catch(err){
    console.error('GF_latest_data_API 失败', err);
  }
}

// 获取直播详情
async function Get_Live_detail_API(live_id) {
  let params = {
    live_id: live_id,
  };
  try{
    // console.log('Get_Live_detail_API 成功', res);
    return await decLiveApi.Live_detail_API(params);
  }catch(err){
    console.error('Get_Live_detail_API 失败', err);
  }
}

const NextPageFlag = computed(() => ((indexItems.value.length) % 10 === 0) && ((activeVideoIndex.value+1) > 0));
watch(NextPageFlag, (isNextPage) => {
  // console.log('next',isNextPage);
  if (isNextPage) {
    // console.log('Next Page');
    return GF_latest_data('', '', PRE_ID.value, '5');
  }

});

onBeforeMount(()=>{})
onMounted(()=>{
  init();
})
onReachBottom(()=>{
  // console.log('123');
  // for(let i = 0;i<videoOnceLength;i++){
  // 	videoItems.value.push(videoItem);
  // }
})
function testReachBottom(e){
  // console.log('11111')
  // console.log(e)//在这里调用追加数据的方法即可
}


</script>

<style scoped>
/* 将高度变为自动100% */
/* #ifdef H5 */
uni-page-body{
  height: 100%;
}

/* #endif */


.page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}

.content{
  /* background-color: #8f8f94; */
  width: 100%;
  height: 100%;
}



.video-swiper{
  width: 100%;
  height: 100%;
}

.video-swiper-item{
  width: 100%;
  height: 100%;
}

/*  */
.page-scroll{
  width: 100%;
  height: 100%;
}

@media screen and (min-width: 600px) {
	.toptab-bar{
		width: 100%;
	}
}
</style>
